package ink.ykb.mq.config;

import java.util.Map;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RabbitTemplateUtil {
	
	  @Autowired
	  private RabbitTemplate rabbitTemplate;
	
	  /**
	   * 发送延迟队列消息
	   * @param exchange
	   * @param routingKey
	   * @param delay
	   * @param msg
	   */
	  public void sendDelayMsg(String exchange,String routingKey,DelayTime delay,String msg) {
	    MessageProperties messageProperties = new MessageProperties();
	    Message message = new Message(msg.getBytes(), messageProperties);
	    //=====================插件方式实现==============================
//	    messageProperties.setDelay(delay);
//	    rabbitTemplate.send(DeadDirectRabbitConfig.DELAY_TEST_EXCHANGE, DeadDirectRabbitConfig.DELAY_TEST_QUEUE, message);
	    
	    //=====================TTL和DLX实现==============================
	    messageProperties.setHeader("delay-exchange", exchange);
	    messageProperties.setHeader("delay-routing-key", routingKey);
	    rabbitTemplate.send(DeadDirectRabbitConfig.DELAY_PER_EXCHANGE+"_"+delay.name().toLowerCase(), DeadDirectRabbitConfig.DELAY_PER_QUEUE+"_"+delay.name().toLowerCase(), message);
	    
	  }
	  
	  public void sendDelayMsg(DelayTime delay,Message message) {
	    //=====================插件方式实现==============================
//      rabbitTemplate.send(DeadDirectRabbitConfig.DELAY_TEST_EXCHANGE, DeadDirectRabbitConfig.DELAY_TEST_QUEUE, message);
        
        //=====================TTL和DLX实现==============================
	    MessageProperties messageProperties = message.getMessageProperties();
	    Map<String, Object> headers = messageProperties.getHeaders();
	    if(headers.get("delay-exchange") == null) {
	      throw new RuntimeException("参数delay-exchange不能为空");
	    }
	    if(headers.get("delay-routing-key") == null) {
	      throw new RuntimeException("参数delay-routing-key不能为空");
	    }
        rabbitTemplate.send(DeadDirectRabbitConfig.DELAY_PER_EXCHANGE+"_"+delay.name().toLowerCase(), DeadDirectRabbitConfig.DELAY_PER_QUEUE+"_"+delay.name().toLowerCase(), message);
	  }
	  
	  /**
	   * 发送消息
	   * @param exchange
	   * @param queue
	   * @param msg
	   */
	  public void sendMsg(String exchange,String queue,String msg) {
	      rabbitTemplate.convertAndSend(exchange,queue,msg);
	  }
	  public void sendMsg(String exchange,String queue,Message message) {
		  rabbitTemplate.send(exchange,queue,message);
	  }

}
